package org.groovymud.object.registry.persistence;

import com.thoughtworks.xstream.XStreamException;
import org.groovymud.object.MudObject;
import org.groovymud.object.registry.MudCloneException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public abstract class MudDataPersistence<T> {

	public abstract void serialize(T object, OutputStream out);

	public abstract T deserializeObject(InputStream xmlIn);

	/**
	 * Loads an object from a datasource, using the given object handle. 
	 *
	 * The object handle could be a file name or id, and implementations will
	 * guarentee to load the object saved with "equal" handles. 
	 * 
	 * @param objectHandle
	 * @return
	 * @throws DataPersistenceException
	 */
	public abstract T loadObject(String objectHandle) throws DataPersistenceException;

	/**
	 * saves a particular object to the data store, using the object handle
	 * provided. 
	 * 
	 * Object handles saved should correlate with the loadObject method's 
	 * handle when loading.
	 * 
	 * @param objectHandle
	 * @param object
	 * @throws DataPersistenceException
	 */
	public abstract void saveObject(String objectHandle, T object) throws DataPersistenceException;

	public abstract boolean deleteObject(String objectHandle);

    public T cloneObject(T o) throws MudCloneException {
            if (o == null) {
                throw new IllegalArgumentException("object cannot be null");
            }
            T copy;
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                serialize(o, out);
                InputStream in = new ByteArrayInputStream(out.toByteArray());
                copy = deserializeObject(in);
            } catch (XStreamException e) {
                throw new MudCloneException("could not clone object "+o, e);
            }
            return copy;
        }

    public abstract void clean();
}
